package com.bridgetree.jubaocrm.ui;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.JsonObjectPostRequest;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.LoginInterface;

/**
 * 个人档案
 */
public class PersonEditDocumentActivity extends Activity {
	private final String TAG = "PersonDocumentActivity";
	private Context mContext;
	private LoginInterface mLoginInterface;
	private InputMethodManager mInputMethodManager;
	private EditText main_doc_ed_phone;
	private EditText main_doc_ed_email;
	private EditText main_doc_ed_name;
	private Button main_doc_ed_sex;
	private RelativeLayout main_persedit_RelativeLayout;
	private TextView select_nan;
	private TextView select_nv;

	private String fullname = "";
	private String cell = "";
	private String email = "";
	private String sex = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_persondoc_edit);
		mContext = this;

		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}

		mInputMethodManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
		main_doc_ed_phone = (EditText) findViewById(R.id.main_doc_ed_phone);
		main_doc_ed_email = (EditText) findViewById(R.id.main_doc_ed_email);
		main_doc_ed_name = (EditText) findViewById(R.id.main_doc_ed_name);
		main_doc_ed_sex = (Button) findViewById(R.id.main_doc_ed_sex);
		main_persedit_RelativeLayout = (RelativeLayout) findViewById(R.id.main_persedit_RelativeLayout);
		select_nan = (TextView) findViewById(R.id.select_nan);
		select_nv = (TextView) findViewById(R.id.select_nv);
		if (intent.getExtras() != null) {
			mLoginInterface = (LoginInterface) intent.getExtras().getSerializable("LoginInterface");
			fullname=intent.getExtras().getString("fullname");
			cell=intent.getExtras().getString("cell");
			email=intent.getExtras().getString("email");
			sex=intent.getExtras().getString("sex");
			main_doc_ed_phone.setText(cell);
			main_doc_ed_email.setText(email);
			main_doc_ed_name.setText(fullname);
			main_doc_ed_sex.setText(sex);
		}

		findViewById(R.id.main_doc_RelativeLayout_back).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						finish();
					}
				});

		findViewById(R.id.main_doc_bt_ok).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						if(mLoginInterface!=null){
							getPersonEditDocument();
						}
					}
				});
		main_doc_ed_sex.setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						main_persedit_RelativeLayout.setVisibility(View.VISIBLE);
					}
				});
		select_nan.setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						main_persedit_RelativeLayout.setVisibility(View.GONE);
						main_doc_ed_sex.setText("男");
					}
				});
		select_nv.setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						main_persedit_RelativeLayout.setVisibility(View.GONE);
						main_doc_ed_sex.setText("女");
					}
				});

	}

	private void openDailogs(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title).setMessage(content)
		.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (content != null && content.trim().equals("用户不存在")) {
					// finish();
				}
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(mContext);
				}

			}
		}).show();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (getCurrentFocus() != null
					&& getCurrentFocus().getWindowToken() != null) {
				mInputMethodManager.hideSoftInputFromWindow(getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
		return super.onTouchEvent(event);
	}

	private void getPersonEditDocument() {
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailogs("网络提示", "网络未连接,请连接网络！");
		} else {
			//			http://crmsoap.woniuwo.cn/profile
			//				参数：cell=13193323391
			//&email=183954573@qq.com
			///&fullname=刘德华
			//&sex=男
			//&user_id=581c3768b5f74d4097ae78ec8d58b8c9
			//&token=dba75fc712b44874acf77bf171947509
			//&validation=gAJ9cQAoVQZsb2NhbGVxAVUFemhfQ05xAl

			HashMap<String, String> mMap = new HashMap<String, String>();
			mMap.put("cell", main_doc_ed_phone.getText().toString());
			mMap.put("email", main_doc_ed_email.getText().toString());
			mMap.put("fullname", main_doc_ed_name.getText().toString());
			mMap.put("sex", main_doc_ed_sex.getText().toString());
			mMap.put("user_id", mLoginInterface.getUser_id());
			mMap.put("token", mLoginInterface.getToken());
			mMap.put("validation", CRMUserBaseInfo.kValication);
			String URL = Network.API_DOMAIN + "/profile";


			final ProgressDialog progressDialog = ProgressDialog.show(this,
					"网络数据", "...Loading...");

			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectPostRequest jsonObjectPostRequest = new JsonObjectPostRequest(
					URL, new Response.Listener<JSONObject>() {

						@Override
						public void onResponse(JSONObject response) {
							ProgressDialogUtil.dissmis(progressDialog);
							try {
								System.out.println("修改个人档案  response=" + response);
								if (!response.isNull("errors")) {
									String errors = response.get("errors")
									.toString();
									if (errors.equals("[]")) {
										Toast.makeText(mContext, "修改档案成功",Toast.LENGTH_LONG).show();
										finish();
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response
											.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr
												.length(); i++) {
													JSONObject jsonObj2 = jsonArr
													.getJSONObject(i);
													if (!jsonObj2
															.isNull("desc")) {
														String desc = jsonObj2
														.getString("desc");
														openDailogs("失败提示", desc);
														mLoginError
														.setDesc(desc);
													}
													if (!jsonObj2
															.isNull("value")) {
														String value = jsonObj2
														.getString("value");
														mLoginError
														.setValue(value);
													}
												}
											}
										}
									}
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							ProgressDialogUtil.dissmis(progressDialog);
							Toast.makeText(mContext, "网络未连接！",
									Toast.LENGTH_LONG).show();
						}
					}, mMap);
			requestQueue.add(jsonObjectPostRequest);
		}
	}

}